<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container" style="overflow:hidden">
      <el-button class="filter-item" icon="el-icon-download" type="primary" v-waves  @click="handleDownload" :loading="downloadLoading">{{$t('coupons.Export')}}</el-button>
      <el-button class="filter-item" icon="el-icon-circle-plus-outline" type="primary" v-waves  @click="dialogFormVisible = true">{{$t('coupons.Add')}}</el-button>
    </div>
    <!--表格 -->
    <el-table :data="list" :element-loading-text="$t('coupons.give_me_time')" v-loading="loading.list" border fit highlight-current-row style="width: 100%">
      <el-table-column prop="index" :label="$t('coupons.Number')"> </el-table-column>
      <el-table-column prop="couponName" :label="$t('coupons.Coupon_name')"> </el-table-column>
      <el-table-column prop="couponType" :label="$t('coupons.Coupon_type')"> </el-table-column>
      <el-table-column prop="couponPrice" :label="$t('coupons.Coupon_amount')"> </el-table-column>
      <el-table-column prop='expiryTime' :label="$t('coupons.Validity_period')"> </el-table-column>
      <el-table-column prop='district' :label="$t('coupons.Using_range')"> </el-table-column>
      <el-table-column prop='userId' :label="$t('coupons.Distributed_object')"> </el-table-column>
      <el-table-column prop='ctime' :label="$t('coupons.Distributed_time')"> </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <!-- 新增优惠券 -->
    <el-dialog :title="$t('coupons.Add_coupon')" :visible.sync="dialogFormVisible" >
      <el-form :model="form" :rules='bindRules' ref="bindForm" label-position="right" label-width="120px">
        <el-form-item :label="$t('coupons.Coupon_name')"  prop="couponName">
          <el-input v-model="form.couponName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('coupons.Coupon_amount')"  prop='couponPrice'>
          <el-input v-model="form.couponPrice" type="number"></el-input>
        </el-form-item>
       <el-form-item :label="$t('coupons.Country')" prop='agentArea'>
          <el-radio-group @change="form.district = '';p = ''" v-model="country">
            <el-radio :label="1">{{$t('coupons.China')}}</el-radio>
            <el-radio :label="2">{{$t('coupons.Australia')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('coupons.Area')" prop="agentArea">
          <!-- 添加key 让组件重新渲染 -->
          <pcq
            :key="country"
            :level='2' 
            label='NAME'
            :address='address'
            @change='onAddressChange'
          ></pcq>
        
        </el-form-item>  
        <el-form-item :label="$t('coupons.Validity_period')" >
          <el-date-picker
            v-model="form.expiryTime"
            type="date"
            :placeholder="$t('coupons.Select_date')"
            value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('coupons.Distributed_object')"  prop='couponType'>
          <el-radio-group v-model="form.couponType">
            <el-radio :label="2">{{$t('coupons.All_users')}}</el-radio>
            <el-radio :label="1">{{$t('coupons.Personal_ID')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
            v-if="form.couponType == 1" 
            :error="$t('coupons.User_ID')"
            prop="userId"
            :rules="[
              { required: true, message: this.$t('coupons.User_id_cannot_be_empty')},
            ]"
          >
          <el-input v-model="form.userId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('coupons.Cancel')}}</el-button>
        <el-button type="primary" @click="addCoupon">{{$t('coupons.Submit')}}</el-button>
      </div>
    </el-dialog>
    <!-- 回到顶部 -->
    <BackToTop></BackToTop>
  </div>
</template>
<script>
import { getCouponList, addCouponInBack, exportExcel} from '@/api/coupon'
import { parseTime } from '@/utils/index'
import BackToTop from '@/components/BackToTop'
import pcq from '@/components/Address'
import { address } from '@/utils/getAddress'
import { Aus } from '@/utils/Australlia'
export default {
  name: 'coupon_list',
  computed:{
    address () {
      if (this.country === 1) {
        return address
      }
      let temp = Aus.map(item => {
        return {
          ...item,
          AREA_ID: item.id,
          NAME: item.name,
          FID: item.fid
        }
      })
      return temp
    }
  },
  components: {
    BackToTop,
    pcq
  },
  data() {
    return {
      country: 2,
      timer: '',
      loading: {
        list: false
      },
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
      },
      list:null,
      dialogFormVisible: false,
      form: {
        couponName: '',
        couponPrice:'',
        expiryTime:'',
        couponType: 2,
        userId:'',
        district: ''
      },
      agentProvince:'',
      agentCity:'',
      agentArea:'',
      downloadLoading: false,
      formLabelWidth: '120px',
      bindRules:{
        couponName: [
          { required: true, message: this.$t('coupons.Please_enter_a_name'), trigger: 'blur' }
        ],
        couponPrice: [
          { required: true, message: this.$t('coupons.Please_enter_the_amount'), trigger: 'blur' }
        ],
        couponType: [
          { required: true, message: this.$t('coupons.Please_choose_the_type'), trigger: 'blur' }
        ],
      },
      agentProvince: '',
      agentCity: '',
    }
  },
 
  created() {
    this.getList()
  },
  methods: {
    onAddressChange (val) {
      let [p, district] = val
      this.form.district = district
    },
    //获取优惠券列表
    async getList() {
      this.loading.list = true
      try {
        let query = Object.assign({}, this.form, this.listQuery)
        const { data } = await getCouponList(query)
        // 循环解析数据
        for(var i = 0; i<data.records.length;i++)
        {
          data.records[i].couponType = data.records[i].couponType == 1 ? this.$t('coupons.personal'):this.$t('coupons.All')
          data.records[i].expiryTime = parseTime(data.records[i].expiryTime).split(' ')[0]
          data.records[i].ctime = parseTime(data.records[i].ctime)
        }
        this.list = data.records.map((item, index) => ({index: index + 1, ...item}))
        this.total = data.total
      } catch (error) { 

      }
      this.loading.list = false     
    },
    // 添加优惠券
    addCoupon(){
      this.$refs['bindForm'].validate(async (valid) => {
      if(valid){ 
        console.log(this.timer)
        this.loading.list = true
        try {
          const { data } = await addCouponInBack(this.form)
          this.dialogFormVisible = false
          this.$message({
          type: 'success',
          message: this.$t('coupons.Added_successfully')
        });
        this.$refs['bindForm'].resetFields()
        this.getList()
        }catch(error){

        }
        this.loading.list = false
      }  
      })
    },
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [this.$t('coupons.Coupon_name'), this.$t('coupons.Coupon_type'), this.$t('coupons.Coupon_amount'),this.$t('coupons.Validity_period'),this.$t('coupons.Using_range'), this.$t('coupons.Distributed_object'),this.$t('coupons.Distributed_time')]
        const filterVal = ['couponName', 'couponType', 'couponPrice','expiryTime','district', 'userId','ctime']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.$t('coupons.Coupon_list')
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {     
        return v[j]
      }))
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    //将时间戳转化成日期字符串
    formatDate(date, offset){
      if(date && typeof date  == 'object' ){
          const d = date[offset];
          return new Date(d).getTime()
      }
      return ''
    },
  }
}
</script>
<style lang="scss" scoped>
  /deep/   .el-carousel__container{
  height:500px !important;
}
  
</style>
